/* eslint-disable indent */
import moment from 'moment';
// 获取今天0:0的时间到当前时间
export function getTodayTimes() {
  const curr = new Date();
  const year = curr.getFullYear();
  const month = curr.getMonth() + 1 < 10 ? '0' + (curr.getMonth() + 1) : curr.getMonth() + 1;
  const day = curr.getDate() < 10 ? '0' + curr.getDate() : curr.getDate();
  return `${year}-${month}-${day}`;
}
// 获取最近一周的时间
export function getCurrentWeek() {
  const now = new Date();
  const week = now.getTime() - 6 * 24 * 60 * 60 * 1000;
  const weekDate = new Date(week);
  const year = weekDate.getFullYear();
  const month =
    weekDate.getMonth() + 1 < 10 ? '0' + (weekDate.getMonth() + 1) : weekDate.getMonth() + 1;
  const day = weekDate.getDate() < 10 ? '0' + weekDate.getDate() : weekDate.getDate();
  return {
    start_date: `${year}-${month}-${day}`,
    end_date: getTodayTimes(),
  };
}

// 获取两段日期的中间日期
export function getPartTime(start, end) {
  let start_time = moment(start).valueOf();
  const end_time = moment(end).valueOf();
  const per_day = 24 * 60 * 60 * 1000;
  const timeArr = [];
  while (start_time <= end_time) {
    const times = moment(start_time).format('YYYY-MM-DD');
    timeArr.push(times);
    start_time += per_day;
  }
  return timeArr;
}
export function getHoursTime(start, end) {
  let start_time = start.valueOf();
  const end_time = end.valueOf();
  const per_hour = 60 * 60 * 1000;
  const timeArr = [];
  while (start_time <= end_time) {
    const times = moment(start_time).format('YYYY-MM-DD HH:00');
    timeArr.push(times);
    start_time += per_hour;
  }
  if (timeArr.length > 24) {
    return timeArr.slice(1, 25);
  }
  return timeArr;
}
// 数字按三位分割
export function toThousands(num) {
  return num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}
// 保留同名数据的深度克隆
export const deepClone = (Target, Origin) => {
  let src, copy, prop;
  if (Origin !== null) {
    for (prop in Origin) {
      src = Target[prop];
      copy = Origin[prop];
      if (copy && typeof copy === 'object') {
        if (Object.prototype.toString.call(copy) === '[object Array]') {
          src = src || [];
        } else {
          src = src || {};
        }
        Target[prop] = deepClone(src, copy);
      } else {
        Target[prop] = copy;
      }
    }
    return Target;
  }
};
/**
 * [domainVerify 判断合法域名]
 * @param  {[string]} domain [域名]
 * @return {[array|null]}
 */
export function domainVerify(domain) {
  var strRegex = /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/;
  var Regex = domain.match(strRegex);
  return Regex;
}
// 数组值求和
export function getSum(arr) {
  if (!arr.length) return 0;
  return arr.reduce((item, cur) => {
    return item + cur;
  }, 0);
}
// 流量转换B to KB、MB、GB
export const formatSize = function (d) {
  if (typeof d === 'undefined') {
    return '0 B';
  }
  if (d > 1000 * 1000 * 1000 * 1000) {
    return (d / (1000 * 1000 * 1000 * 1000.0)).toFixed(2) + ' TB';
  } else if (d > 1000 * 1000 * 1000) {
    return (d / (1000 * 1000 * 1000.0)).toFixed(2) + ' GB';
  } else if (d > 1000 * 1000) {
    return (d / (1000 * 1000.0)).toFixed(2) + ' MB';
  } else if (d > 1000) {
    return (d / 1000.0).toFixed(2) + ' KB';
  } else if (d > 0 && d < 1000) {
    return d + ' B';
  }
  return '0 B';
};
// 获取get请求的params
/*
type为要输出的参数 不传则为所有
*/
export const getParams = function (type = false, url = window.location.href) {
  const str = url.substr(url.indexOf('?') + 1);
  const params = new URLSearchParams(str);
  const obj = {};
  for (let item of params.entries()) {
    obj[item[0]] = item[1];
  }
  if (type) {
    return obj[type];
  } else {
    return obj;
  }
};
// 判断数组是否存在重复元素
export const repeatArray = function (arr) {
  const map = {};
  let show = 0;
  arr.forEach((item) => {
    if (map[JSON.stringify(item)]) {
      show = 1;
    } else {
      map[item] = 1;
    }
  });
  return show ? true : false;
};
// IP地址校验
const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
const v4c =
  /^((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)(\.((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)){2}$/;
const v4Str = `(?:${v4Seg}[.]){3}(?:${v4Seg.slice(3, -1).split('|').reverse().join('|')})`;
export const IPv4Reg = new RegExp(`^${v4Str}$`);
const v6Seg = '(?:[0-9a-fA-F]{1,4})';
const v6Str =
  '(?:' +
  `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
  `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
  `(?:${v6Seg}:){5}(?::${v4Str}|(?::${v6Seg}){1,2}|:)|` +
  `(?:${v6Seg}:){4}(?:(?::${v6Seg}){0,1}:${v4Str}|(?::${v6Seg}){1,3}|:)|` +
  `(?:${v6Seg}:){3}(?:(?::${v6Seg}){0,2}:${v4Str}|(?::${v6Seg}){1,4}|:)|` +
  `(?:${v6Seg}:){2}(?:(?::${v6Seg}){0,3}:${v4Str}|(?::${v6Seg}){1,5}|:)|` +
  `(?:${v6Seg}:){1}(?:(?::${v6Seg}){0,4}:${v4Str}|(?::${v6Seg}){1,6}|:)|` +
  `(?::(?:(?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
  ')(?:%[0-9a-zA-Z]{1,})?';
export const IPv6Reg = new RegExp(`^${v6Str}$`);
export function isIPv4(str) {
  return IPv4Reg.test(str) || v4c.test(str);
}
export function isIPv6(str) {
  return IPv6Reg.test(str);
}
export function isIPDuan(str) {
  const norml =
    /^(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))-(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))$/.test(
      str
    );
  const ipv4c =
    /^((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)(\.((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)){2}-((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)(\.((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)){2}$/.test(
      str
    );
  return norml || ipv4c;
}
export function isIPv6Duan(str) {
  const ipv6Duan = new RegExp(`^(${v6Str})-(${v6Str})$`);
  return ipv6Duan.test(str);
}
export function isIP(str) {
  if (isIPv4(str)) return 4;
  if (isIPv6(str)) return 6;
  if (isIPDuan(str)) return 2;
  if (isIPv6Duan(str)) return 3;
  return 0;
}
export const cidrRegexStr = '(?:\\/\\d{1,3})?';
export const ipOrCidrRegexpStr = `(?:${v4Str}|${v6Str})${cidrRegexStr}`;
export function ipValid({ ip, enableCidr = false }) {
  let ipStr = ip;
  if (enableCidr) {
    const [prefix, ...suffix] = ipStr.split('/');
    if (suffix.length > 1 && !/^\d+$/.test(suffix.join('/'))) return false;
    ipStr = prefix;
  }

  return isIP(ipStr) > 0;
}

export const accurateDict = {
  base: '基础',
  custom: '自定义',
  cookie: 'Cookie',
  referer: 'Referer',
  method: 'HTTP-Method',
  ua: 'User-Agent',
  x_forwarded_for: 'X-Forwarded-For',
  uri: 'URI',
  uri_query_string: 'URI-Query-String',
  content_type: 'Content-Type',
  content_length: 'Content-Length',
  post_body: 'Post-Body',
  client_ip: 'Client-IP',
  in: '包含',
  nin: '不包含',
  eq: '等于',
  neq: '不等于',
  bl: '属于',
  nbl: '不属于',
  vlt: '值小于',
  veq: '值等于',
  vgt: '值大于',
  llt: '长度小于',
  leq: '长度等于',
  lgt: '长度大于',
  nex: '不存在',
  deny: '阻断',
  allow: '放行',
  log: '记录',
  js_challenge: 'JS挑战',
  captcha: '验证码',
};

export const warnInfoDict = {
  wafcfg: '未开启防火墙的拦截模式',
  cache_type: '未开启访问加速功能',
  site_shield: '未开启内容监测功能',
  ssl: '未设置SSL证书',
  disk_is_full: '您的设备存储空间已达到90%，建议备份并清除部分日志',
};

export const warnInfo = {
  cert_expire_soon: ['您的产品证书即将到期', '/product_info/'],
  system_new_version_available: ['您的系统有待升级的系统版本', '/system_update/'],
  data_new_version_available: ['您的系统有待升级的数据版本', '/system_manage/?type=data_update'],
  ssl_expire_soon: ['您的SSL证书即将到期', '/ssl/'],
  is_origin_pw: ['您的初始密码未修改，建议修改密码', '/user_manage/'],
};

export const getErrorMessage = (err, type = 'message') => {
  if (!err) {
    return '字段为空'
  }
  if (typeof err === 'string') {
    return err;
  } else if(Array.isArray(err)){
    return err[0];
  }else {
    return typeof err[type] === 'object' ? Object.values(err[type])[0] : err[type];
  }
};
// 获取url参数
export const GetQueryString = (search, name) => {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  var r = search.substr(1).match(reg); //search,查询？后面的参数，并匹配正则
  if (r != null) return decodeURI(r[2]);
  return null;
};
// base64返编译
export const base64Decode = (input) => {
  if (input) {
    let rv = window.atob(input);
    rv = encodeURI(rv);
    rv = decodeURIComponent(rv);
    return rv;
  } else {
    return '';
  }
};
export const deal_data=(data, bool)=>{
  if (!data) {
    return
  }
  if (Array.isArray(data) && !bool) {
    return data[0]
  } else if (Object.prototype.toString.call(data) === '[object Object]') {
    if (data.selectedItem.length > 0) {
      if (data.selectedItem.length > 1 || bool) {
        return data.selectedItem.map(item => item.value)
      }
      return data.selectedItem[0].value
    } else {
      return []
    }
  } else {
    return data
  }
}
